package com.xiaoyu.client.ui.activity.home;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoyu.client.ClientConstants;
import com.xiaoyu.client.R;
import com.xiaoyu.client.model.mine.ParticularsBean;
import com.xiaoyu.client.model.nearby.NearbyShopBean;
import com.xiaoyu.client.model.nearby.ShopParam;
import com.xiaoyu.client.model.nearby.ShopTagBean;
import com.xiaoyu.client.model.nearby.ShopTagParam;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.activity.nearby.MyRecommendActivity;
import com.xiaoyu.client.ui.activity.nearby.NearbySearchActivity;
import com.xiaoyu.client.ui.activity.nearby.ShopByTagActivity;
import com.xiaoyu.client.ui.activity.nearby.ShopDetailActivity;
import com.xiaoyu.client.ui.activity.nearby.ShopRecomAddActivity;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.SpacesItemDecoration;
import com.xiaoyu.commonlib.ui.adapter.AllPowerfulAdapter;
import com.xiaoyu.commonlib.ui.base.BaseActivityWithTitle;
import com.xiaoyu.commonlib.utils.AccessLocation;
import com.xiaoyu.commonlib.utils.CCircleImageView;
import com.xiaoyu.commonlib.utils.LongitudeAndLatitude;
import com.xiaoyu.commonlib.utils.ToastUtil;
import com.xiaoyu.commonlib.utils.UIUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @author jx
 * @date 创建时间 2018/11/8
 * @Description 附近商家
 */
public class NearbyShopsActivity extends BaseActivityWithTitle {
    @BindView(R.id.nearby_shops_search_btn)
    EditText mSearchBtn;//搜索按钮
    @BindView(R.id.activity_nearby_shop_refresh_layout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.activity_nearby_shop_list_container)
    RecyclerView mShopContainer;//附近商铺列表容器
    @BindView(R.id.nearby_shops_tag_list_container)
    RecyclerView mTagContainer;//附近商铺类别列表容器
    private View mView;
    @BindView(R.id.activity_nearby_shops_empty_page)
    ImageView mEmptyPage;
    @BindView(R.id.activity_nearby_shops_address)//地理位置
            TextView mNearbyTxt;

    public static final String SHOP_TAG = "shop_tag";
    private List<ShopTagParam> mTagList = new ArrayList<>();//店铺类别列表
    private List<ShopParam> mShopList = new ArrayList<>();//店铺数据列表
    private AllPowerfulAdapter mTagAdapter;//店铺类别列表适配器
    private AllPowerfulAdapter mShopAdapter;//店铺列表适配器
    private int page = 1;//当前页数
    private int totalPage;//总页数
    public LocationClient mLocationClient = null;
    private String lat;//纬度
    private String lng;//经度

    @Override
    protected void loadContentView(ViewGroup parent) {
        setTitleText("附近商家");
        mView = LayoutInflater.from(this).inflate(R.layout.activity_nearby_shops, parent, true);
        ButterKnife.bind(this);
        initUI();
    }

    @Override
    protected void onResume() {
        super.onResume();
        page = 1;
        mShopList.clear();
        mTagList.clear();
        mLocationClient.start();
        getShopTagInfo();
    }


    private void initUI() {
        //初始化定位对象
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setCoorType("GCJ02");
        option.setScanSpan(1000);
        option.setOpenGps(true);
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);


        //店铺类别列表
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
//        GridLayoutManager layoutManager = new GridLayoutManager(this,5);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mTagContainer.setLayoutManager(layoutManager);
        mTagContainer.addItemDecoration(new SpacesItemDecoration(UIUtils.dip2px(15), 2));
        setTagAdapter(mTagList);

        //店铺列表
        mShopContainer.setLayoutManager(new LinearLayoutManager(this));
        setShopAdapter(mShopList);

        //上拉下拉刷新设置
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsHeader(context);
            }
        });
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });

        mRefreshLayout.setOnRefreshListener(onRefreshListener);
        mRefreshLayout.setOnLoadMoreListener(onLoadMoreListener);
        mRefreshLayout.setNoMoreData(false);

        mSearchBtn.setOnClickListener(this);
    }

    /**
     * 定位监听
     */
    private BDAbstractLocationListener myListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            Log.i("xiaoyuu", "经纬度  经度： " + bdLocation.getLongitude() + "   纬度：  " + bdLocation.getLatitude()
                    + "   街道： " + bdLocation.getStreet() + "   type = " + bdLocation.getLocType()
                    + "   省份 ： " + bdLocation.getProvince() + "  城市： " + bdLocation.getCity() + "  addstr : " + bdLocation.getAddrStr()
                    + "  描述：" + bdLocation.getLocationDescribe());
            mNearbyTxt.setText(bdLocation.getProvince());
            lat = String.valueOf(bdLocation.getLatitude());
            lng = String.valueOf(bdLocation.getLongitude());
            getNearbyShops();
            mLocationClient.stop();
        }
    };


    /**
     * 店铺列表适配器
     *
     * @param mShopList
     */
    private void setShopAdapter(List<ShopParam> mShopList) {
        mShopAdapter = new AllPowerfulAdapter<ShopParam>(R.layout.service_station_item, mShopList, new AllPowerfulAdapter.OnClickListener<ShopParam>() {
            @Override
            public void setOnClick(BaseViewHolder baseViewHolder, ShopParam shopParam, int position) {
                Intent intent = new Intent(NearbyShopsActivity.this, ShopDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt(ClientConstants.FROM, ClientConstants.FROM_NEARBY_STORE);
                bundle.putString(ClientConstants.STORE_ID, shopParam.getStoreId());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        }) {
            @Override
            protected void convert(BaseViewHolder baseViewHolder, ShopParam param) {
                super.convert(baseViewHolder, param);
                ImageView shopImg = baseViewHolder.getView(R.id.service_station_item_img);//店铺图片
                Glide.with(NearbyShopsActivity.this).load(param.getStoreImageUrl()).into(shopImg);
                baseViewHolder.setText(R.id.service_station_item_title, param.getStoreName());//店铺名字
                baseViewHolder.setText(R.id.service_station_item_location, param.getStoreCity() + param.getStoreAddress());//店铺地址
                baseViewHolder.setText(R.id.service_station_item_distance, param.getDistance());//店铺距离
                LinearLayout tagLayout = baseViewHolder.getView(R.id.service_station_item_tag_layout);
                tagLayout.removeAllViews();
                for (int i = 0; i < param.getTagList().size(); i++) {
                    TextView textView = new TextView(NearbyShopsActivity.this);
                    textView.setPadding(UIUtils.dip2px(10), 0, UIUtils.dip2px(10), 0);
                    textView.setBackgroundColor(Color.parseColor(param.getTagList().get(i).getTagColor()));
                    textView.setText(param.getTagList().get(i).getTagName());
                    textView.setTextSize(11);
                    textView.setGravity(Gravity.CENTER);
                    textView.setTextColor(Color.WHITE);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, UIUtils.dip2px(22));
                    if (i == 0) {
                        layoutParams.setMargins(0, 0, 0, 0);
                    } else {
                        layoutParams.setMargins(UIUtils.dip2px(12), 0, 0, 0);
                    }
                    tagLayout.addView(textView, layoutParams);
                }

            }
        };
        mShopContainer.setAdapter(mShopAdapter);
    }


    /**
     * 店铺类别列表适配器
     */
    private void setTagAdapter(List<ShopTagParam> mTagList) {
        mTagAdapter = new AllPowerfulAdapter<ShopTagParam>(R.layout.item_shop_tag, mTagList, new AllPowerfulAdapter.OnClickListener<ShopTagParam>() {
            @Override
            public void setOnClick(BaseViewHolder baseViewHolder, ShopTagParam shopTagParam, int position) {
                Intent intent = new Intent(NearbyShopsActivity.this, ShopByTagActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable(SHOP_TAG, shopTagParam);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        }) {
            @Override
            protected void convert(BaseViewHolder baseViewHolder, ShopTagParam param) {
                super.convert(baseViewHolder, param);
                CCircleImageView tagImg = baseViewHolder.getView(R.id.item_shop_tag_img);
                Glide.with(NearbyShopsActivity.this).load(param.getTagImg()).into(tagImg);
//                baseViewHolder.setText(R.id.item_shop_tag_name, param.getTagName());
                baseViewHolder.getView(R.id.item_shop_tag_layout).setVisibility(View.VISIBLE);
                baseViewHolder.getView(R.id.item_shop_tag_img_name).setVisibility(View.GONE);

            }
        };
        mTagContainer.setAdapter(mTagAdapter);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        Intent intent;
        if (v == mSearchBtn) {//搜索
            intent = new Intent(this, NearbySearchActivity.class);
            startActivity(intent);
        }
    }


    //刷新监听
    private OnRefreshListener onRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh(@NonNull RefreshLayout refreshLayout) {
            page = 1;
            mShopList.clear();
            mShopAdapter.notifyDataSetChanged();
            getNearbyShops();
            mRefreshLayout.finishRefresh();
        }
    };

    //加载更多
    private OnLoadMoreListener onLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            if (page < totalPage) {
                page = page + 1;
                getNearbyShops();
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.setNoMoreData(false);
            } else {
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.setNoMoreData(true);
                mRefreshLayout.finishLoadMoreWithNoMoreData();
                ToastUtil.showBelowToast(NearbyShopsActivity.this, "已经没有更多数据！！！");
            }
        }
    };


    /**
     * 获取附近商铺列表信息
     */
    private void getNearbyShops() {
        showLoading();
        NetworkManager.getNearbyShopAllList(page, lat, lng, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                dissmissLoading();
                parseShopInfoSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
                dissmissLoading();
                if (errorCode.equals("y400")) {
                    mEmptyPage.setVisibility(View.VISIBLE);
                    mShopContainer.setVisibility(View.GONE);
                    mRefreshLayout.setEnableRefresh(false);
                    mRefreshLayout.setEnableLoadMore(false);
                    mEmptyPage.setImageResource(R.mipmap.no_data);
                }
            }
        });
    }

    private void parseShopInfoSuc(String result) {
        if (page == 1) {
            mShopList.clear();
        }
        NearbyShopBean bean = new Gson().fromJson(result, NearbyShopBean.class);
        totalPage = Integer.parseInt(bean.getData().getCount());
        mShopList.addAll(bean.getData().getList());
        if (bean.getData().getList().size() == 0) {
            mEmptyPage.setVisibility(View.VISIBLE);
            mShopContainer.setVisibility(View.GONE);
            mRefreshLayout.setEnableRefresh(false);
            mRefreshLayout.setEnableLoadMore(false);
            mEmptyPage.setImageResource(R.mipmap.no_data);
        }
        mShopAdapter.notifyDataSetChanged();
    }

    /**
     * 获取附近商铺类别
     */
    private void getShopTagInfo() {
        showLoading();
        NetworkManager.getShopTagList(new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                dissmissLoading();
                parseTagInfoSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
                dissmissLoading();
            }
        });
    }

    private void parseTagInfoSuc(String result) {
        ToastUtil.logResult("商铺类别", result);
        ShopTagBean bean = new Gson().fromJson(result, ShopTagBean.class);
        mTagList.addAll(bean.getData());
        mTagAdapter.notifyDataSetChanged();
    }


    //我的推荐
    @OnClick(R.id.my_recommend)
    public void myRecommedClick() {
        startActivity(new Intent(this, MyRecommendActivity.class));
    }


    //推荐入住
    @OnClick(R.id.recommend_to_stay_in)
    public void addRecomClick() {
        startActivity(new Intent(this, ShopRecomAddActivity.class));
    }
}
